﻿
Imports System.Object
Imports VSModel
Imports Cls_Common
Partial Class FrontEnd_Control_Product_AdvanceSearch
    Inherits System.Web.UI.UserControl
    Dim StoreId As Integer
    Dim CateId As Integer
    Dim level As String = -1
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim SearchName As String = Request("SearchName")
            txtTitle.Text = SearchName
            'xu ly jquery khi post back
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "jqueryEnable", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "jqueryEnable", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            getMenu()
            getNhanHieu()
            getDoTuoi()
            getNMauSac()
            getKichCo()
            BindToGrid(1, txtTitle.Text.Trim, "", -1, -1, -1, -1, -1, ddlNhanHieu.SelectedValue)

        End If
    End Sub
    Protected Sub getMenu()
        ddlLoaiSanPham.Items.Clear()
        ddlLoaiSanPham.AppendDataBoundItems = True
        ddlLoaiSanPham.Items.Insert(0, New ListItem("---Tất cả---", "-1"))
        Using data As New VSEntities
            Dim query As List(Of Category) = (From q In data.Categories Order By q.Sort Ascending Select q).ToList
            ddlLoaiSanPham.DataValueField = "CatId"
            ddlLoaiSanPham.DataTextField = "Title"
            If Not query Is Nothing Then
                RecursiveFillTree(query, 0)
            End If
        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Category), ByVal _parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Using data As New VSEntities
            Dim dv As List(Of Category) = (From q In data.Categories Where q.ParentId = _parentID Select q).ToList
            Dim i As Integer
            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).CatId.ToString())
                    ddlLoaiSanPham.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).CatId.ToString()))
                Next
            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub
    Protected Sub getNhanHieu()
        ddlNhanHieu.Items.Clear()
        ddlNhanHieu.AppendDataBoundItems = True
        ddlNhanHieu.Items.Add(New ListItem("---Tất cả---", "-1"))
        Dim brand As Integer = Request("BrandId")
        Using data As New VSEntities
            Dim p = (From q In data.ProductUnits Order By q.ProductUnitName Select q).ToList
            ddlNhanHieu.DataValueField = "ProductUnitID"
            ddlNhanHieu.DataTextField = "ProductUnitName"
            ddlNhanHieu.DataSource = p
            ddlNhanHieu.DataBind()
            ddlNhanHieu.SelectedValue = brand
        End Using

    End Sub
    Protected Sub getDoTuoi()
        ddlDoTuoi.Items.Clear()
        ddlDoTuoi.AppendDataBoundItems = True
        ddlDoTuoi.Items.Add(New ListItem("---Tất cả---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.ProDoTuois Order By q.Title Select q).ToList
            ddlDoTuoi.DataValueField = "Id"
            ddlDoTuoi.DataTextField = "Title"
            ddlDoTuoi.DataSource = p
            ddlDoTuoi.DataBind()
            ddlDoTuoi.SelectedValue = 0
        End Using

    End Sub
    Protected Sub getNMauSac()
        ddlColor.Items.Clear()
        ddlColor.AppendDataBoundItems = True
        ddlColor.Items.Add(New ListItem("---Tất cả---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.ProColors Order By q.Title Select q).ToList
            ddlColor.DataValueField = "Id"
            ddlColor.DataTextField = "Title"
            ddlColor.DataSource = p
            ddlColor.DataBind()
            ddlColor.SelectedValue = 0
        End Using

    End Sub
    Protected Sub getKichCo()
        ddlSize.Items.Clear()
        ddlSize.AppendDataBoundItems = True
        ddlSize.Items.Add(New ListItem("---Tất cả---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.ProSizes Order By q.Title Select q).ToList
            ddlSize.DataValueField = "Id"
            ddlSize.DataTextField = "Title"
            ddlSize.DataSource = p
            ddlSize.DataBind()
            ddlSize.SelectedValue = 0
        End Using

    End Sub
    Private Sub BindToGrid(Optional ByVal ipage As Integer = 1, _
                           Optional ByVal strTitle As String = "", _
                           Optional ByVal strCode As String = "", _
                           Optional ByVal intIsSellOff As Integer = -1, _
                           Optional ByVal intCate As Integer = -1, _
                           Optional ByVal intMauSac As Integer = -1, _
                           Optional ByVal intDoTuoi As Integer = -1, _
                           Optional ByVal intKichCo As Integer = -1, _
                           Optional ByVal intNhanHieu As Integer = -1)
        Using Data As New VSEntities
            Dim intPag_Size As Int32 = 12
            Dim p As List(Of uspProductSearchWeb_Result) = Data.uspProductSearchWeb(strTitle, _
                                                                                    strCode, _
                                                                                    intIsSellOff, _
                                                                                    intCate, _
                                                                                    intMauSac, _
                                                                                    intDoTuoi, _
                                                                                    intKichCo, _
                                                                                    intNhanHieu, _
                                                                                    ipage, intPag_Size).ToList

            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()
                Create_Pager(hidCount.Value, ipage, 12, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
                results_resultsNavigationDiv.Visible = False
            End If

            With rptProduct
                .DataSource = p
                .DataBind()
            End With

        End Using
    End Sub

    Protected Sub rtpProduct_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptProduct.ItemDataBound
        Dim row = CType(e.Item.DataItem, Object)
        Dim img As Image = CType(e.Item.FindControl("img"), Image)
        Dim ltrTitle As Literal = CType(e.Item.FindControl("ltrTitle"), Literal)
        Dim hplImg As HyperLink = CType(e.Item.FindControl("hplImg"), HyperLink)
        Dim hplTitle As HyperLink = CType(e.Item.FindControl("hplTitle"), HyperLink)
        Dim lblSellPrice As Literal = CType(e.Item.FindControl("lblSellPrice"), Literal)
        lblSellPrice.Text = FormatNumber(row.SellPrice.ToString)
        Dim ltrOriginalPrice As Label = CType(e.Item.FindControl("ltrOriginalPrice"), Label)
        ltrOriginalPrice.Text = FormatNumber(row.OriginalPrice.ToString)
        img.ImageUrl = CookedImageURL("210-280", row.ImagePreview.ToString)
        img.AlternateText = row.Title
        img.Style.Add("overflow", "hidden")
        Dim ltrDiscount As Literal = CType(e.Item.FindControl("ltrDiscount"), Literal)
        If Not row.IsSellOff = False Then
            ltrDiscount.Text = CType((((row.OriginalPrice - row.SellPrice) / row.OriginalPrice) * 100), Integer).ToString("#,##0") & "%"
            ltrOriginalPrice.Visible = True
        End If
        Dim ltrNhanHieu As Literal = CType(e.Item.FindControl("ltrNhanHieu"), Literal)
        Dim _ProductId As Integer = row.ProductId
        Using Data As New VSEntities
            Dim _ProductUnitId As Integer = (From q In Data.Products Where q.ProductId = _ProductId Select q.ProductUnitId).FirstOrDefault
            Dim nhanhieu = (From q In Data.ProductUnits Where q.ProductUnitID = _ProductUnitId Select q).FirstOrDefault
            If Not nhanhieu Is Nothing Then
                ltrNhanHieu.Text = nhanhieu.ProductUnitName
            End If
        End Using
        'If ltrDiscount.Text = "0" Then
        '    ltrDiscount.CssClass = "blind"
        '    ltrOriginalPrice.Text = ""
        'End If
        'lblNhanHieu.Text = row.ProductUnitId
        ltrTitle.Text = row.Title
        hplImg.NavigateUrl = MainDomain & row.CateID & "/" & row.QueryString & "-" & row.ProductId.ToString & ".html"
        hplImg.NavigateUrl = MainDomain & row.CateID & "/" & row.QueryString & "-" & row.ProductId.ToString & ".html"


    End Sub

    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub

    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = e.Item.DataItem
            lnkTitle.CssClass = "phantrang_visible"
        Else
            lnkTitle.Text = e.Item.DataItem
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub

    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub


    Protected Sub btnAddCart_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim _ProductID As Integer
        _ProductID = sender.tooltip()
        AddShoppingCart(_ProductID)
        Session("LastURL") = Request.Url
        Response.Redirect(MainDomain & "gio-hang.html")


    End Sub

    Private Sub AddShoppingCart(ByVal _ProductID As String)
        Using Data As New VSEntities
            Dim _cartID As String = Session("CartId")
            Dim check = (From q In Data.ShoppingCarts Where q.CartId = _cartID And q.ProductId = _ProductID Select q).FirstOrDefault
            If check Is Nothing Then
                Dim p As New ShoppingCart
                p.CartId = _cartID
                p.ProductId = _ProductID
                p.UserId = Session("UserId")
                ' p.StoreId = (From q In Data.Products Where q.ProductId = _ProductID Select q.StoreId).FirstOrDefault
                p.Quantity = 1
                Data.ShoppingCarts.AddObject(p)
                Data.SaveChanges()

            End If
        End Using
    End Sub
    Protected Sub btnSearch_Click(sender As Object, e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1, txtTitle.Text.Trim, "", _
                   chkIsselloff.SelectedValue, _
                   ddlLoaiSanPham.SelectedValue, _
                   ddlColor.SelectedValue, _
                   ddlDoTuoi.SelectedValue, _
                   ddlSize.SelectedValue, _
                   ddlNhanHieu.SelectedValue)
    End Sub
End Class
